package org.javaforever.cookieshop.serviceimpl;

import java.util.List;
import org.javaforever.cookieshop.dao.TypeDao;
import org.javaforever.cookieshop.domain.TypeBean;
import org.javaforever.cookieshop.service.TypeService;
import org.javaforever.cookieshop.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.Query;

@Service
public class TypeServiceImpl implements TypeService{
	@Autowired
	protected TypeDao dao;

	@PersistenceContext
	protected EntityManager entityManager;

	@Override
	public void activateAllTypes(String ids) throws Exception{
        String [] idArr = ids.split(",");
        for (String idString : idArr){
            Long id = Long.valueOf(idString);
            dao.activateType(id);
        }
	}

	@Override
	public Boolean activateType(Long id) throws Exception{
        dao.activateType(id);
        return true;
	}

	@Override
	@Transactional
	public Boolean addType(TypeBean type) throws Exception{
        dao.saveAndFlush(type);
        return true;
	}

	@Override
	public void cloneAllTypes(String ids) throws Exception{
        String [] idArr = ids.split(",");
        for (String idString : idArr){
            Long id = Long.valueOf(idString);
            cloneType(id);
        }
	}

	@Override
	public Boolean cloneType(Long id) throws Exception{
        TypeBean type = dao.findTypeFullInfoById(id);
        
        String name = type.getName();
        String shortName = name;
        if (name.contains("_") && StringUtil.isInteger(name.substring(name.lastIndexOf('_')+1,name.length()))) {
            shortName = name.substring(0,name.lastIndexOf('_'));
        }
        List<TypeBean> names = dao.searchTypeIndexedNamesByShortName(shortName);
        int indexNum = 1;
        for (TypeBean type0:names) {
            String _name = type0.getName();
            if (_name.contains("_") && StringUtil.isInteger(_name.substring(_name.lastIndexOf('_')+1,_name.length()))) {
                int index = Integer.valueOf(_name.substring(_name.lastIndexOf('_')+1,_name.length()));
                if (index >= indexNum) {
                    indexNum = index + 1;
                }
            }
        }
        String indexName = shortName + "_" + indexNum;
        TypeBean type1 = type.clone();
        type1.setId(null);
        type1.setName(indexName);
        addType(type1);
        return true;
	}

	@Override
	public Integer countActiveTypeRecords() throws Exception{
        return dao.countActiveTypeRecords();
	}

	@Override
	public Integer countSearchTypesByFieldsRecords(TypeBean type) throws Exception{
        String jpql = "select count(*) as countNum from TypeBean t where 1=1 ";
        if (type.getName() != null) {
            jpql += " and t.name like CONCAT('%', '"+type.getName()+"','%')";
        }
        if (type.getActive() != null) {
            jpql += " and t.active = "+type.getActive();
        }
        Query query = entityManager.createQuery(jpql);
        Long count = (Long) query.getSingleResult();
        return count.intValue();
	}

	@Override
	public void deleteAllTypes(String ids) throws Exception{
        String [] idArr = ids.split(",");
        for (String idString : idArr){
            Long id = Long.valueOf(idString);
            dao.deleteType(id);
        }
	}

	@Override
	public Boolean deleteType(Long id) throws Exception{
        dao.deleteType(id);
        return true;
	}

	@Override
	public TypeBean findTypeById(Long id) throws Exception{
        return dao.findTypeById(id);
	}

	@Override
	public TypeBean findTypeByName(String name) throws Exception{
        return dao.findTypeByName(name);
	}

	@Override
	public List<TypeBean> listActiveTypes() throws Exception{
        return dao.listActiveTypes();
	}

	@Override
	public List<TypeBean> listAllTypes() throws Exception{
        return dao.listAllTypes();
	}

	@Override
	public List<TypeBean> searchTypesByFields(TypeBean type) throws Exception{
        String jpql = "from TypeBean t where 1=1 ";
        if (type.getName() != null) {
            jpql += " and t.name like CONCAT('%', '"+type.getName()+"','%')";
        }
        if (type.getActive() != null) {
            jpql += " and t.active = "+type.getActive();
        }
        Query query = entityManager.createQuery(jpql);
        List<TypeBean> results = query.getResultList();
        return results;
	}

	@Override
	public List<TypeBean> searchTypesByFieldsByPage(TypeBean type,Integer pagesize,Integer pagenum) throws Exception{
        Integer start = (pagenum-1)*pagesize;
        Integer limit = pagesize;
        String jpql = "from TypeBean t where 1=1 ";
        if (type.getName() != null) {
            jpql += " and t.name like CONCAT('%', '"+type.getName()+"','%')";
        }
        if (type.getActive() != null) {
            jpql += " and t.active = "+type.getActive();
        }
        Query query = entityManager.createQuery(jpql);
        query.setFirstResult(start); // 设置起始位置
        query.setMaxResults(limit); // 设置返回结果数量
        List<TypeBean> results = query.getResultList();
        return results;
	}

	public void setDao(TypeDao dao){
		this.dao = dao;
	}

	@Override
	public void softDeleteAllTypes(String ids) throws Exception{
        String [] idArr = ids.split(",");
        for (String idString : idArr){
            Long id = Long.valueOf(idString);
            dao.softDeleteType(id);
        }
	}

	@Override
	public boolean softDeleteType(Long id) throws Exception{
        dao.softDeleteType(id);
        return true;
	}

	@Override
	public Boolean toggleOneType(Long id) throws Exception{
        TypeBean type = dao.findTypeById(id);
        if (type.getActive()==false) {
            dao.toggleType(id);
        }
        else {
            Integer count = dao.countActiveTypeRecords();
            if (count > 1){
                dao.toggleType(id);
            }
        }
        return true;
	}

	@Override
	public Boolean toggleType(Long id) throws Exception{
        dao.toggleType(id);
        return true;
	}

	@Override
	@Transactional
	public Boolean updateType(TypeBean type) throws Exception{
        entityManager.merge(type);
        return true;
	}

}
